import React, { MouseEvent, useRef } from "react";
import { useNavigate } from "react-router-dom";

import { useAppContext } from "../../services/context";
import { login } from "../../services/apis";
import * as constant from "../../services/constant";
import { getItem } from "../../services/storage";

import "./index.scss";

export default function Login() {
  const usernameRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);
  const nav = useNavigate();
  const { context, setContext } = useAppContext();

  const onSubmit = (event: MouseEvent) => {
    event.preventDefault();
    const username = usernameRef.current?.value;
    const password = passwordRef.current?.value;

    if (username && password) {
      login({ username, password }).then((result) => {
        const token = getItem(constant.KEY_TOKEN);
        const permits = getItem(constant.KEY_PERMITS);
        if (!permits) {
          nav("/login", { replace: true });
          return;
        }
        const permissions = JSON.parse(permits);
        setContext({ permissions, token });
        nav("/home", { replace: false});
      });
    }
  };

  return (
    <div className="container_login">
      <div className="box">
        <div className="form">
          <label>
            <span>用户名:</span>
            <input ref={usernameRef} type="text" name="username" />
          </label>
          <label>
            <span>密码:</span>
            <input ref={passwordRef} type="password" name="password" />
          </label>
          <button onClick={onSubmit}>登陆</button>
        </div>
      </div>
    </div>
  );
}
